import { oidcConfig } from "./config"
import request from '/@/utils/request';

class AuthService {
  // 生成授权URL
  getAuthorizationUrl(state = null, nonce = null) {
    const params = new URLSearchParams({
      response_type: oidcConfig.responseType,
      client_id: oidcConfig.clientId,
      redirect_uri: oidcConfig.redirectUri,
      scope: oidcConfig.scope,
      state: state || this.generateRandomString(),
      nonce: nonce || this.generateRandomString()
    })
    
    let authUrl = `${oidcConfig.issuer}${oidcConfig.endpoints.authorization}?${params}`
    return authUrl  
  }

  // 处理授权回调
  async handleCallback(code: any, state: any) {
    try {
       const response =  await request({
            url: '/user/auth/callback',
            method: 'post',
            data: {
                code,
                state,
                redirect_uri: oidcConfig.redirectUri
            }
        })
      
      const { access_token, id_token, refresh_token, user_info } = response.data
      
      // 存储令牌
      localStorage.setItem('access_token', access_token)
      localStorage.setItem('id_token', id_token)
      localStorage.setItem('refresh_token', refresh_token)
      localStorage.setItem('user_info', JSON.stringify(user_info))
      
      return user_info
    } catch (error) {
      console.log('Token exchange failed:', error)
      throw error
    }
  }

  // 刷新令牌
  async refreshToken() {
    const refreshToken = localStorage.getItem('refresh_token')
    if (!refreshToken) {
      throw new Error('No refresh token available')
    }

    try {
      const response = await request({
        url: '/user/auth/refresh',
        method: 'post',
        data: {
          refresh_token: refreshToken
        }
      })
      
      const { access_token, id_token, refresh_token } = response.data
      localStorage.setItem('access_token', access_token)
      localStorage.setItem('id_token', id_token)
      localStorage.setItem('refresh_token', refresh_token)
      
      return access_token
    } catch (error) {
      this.logout()
      throw error
    }
  }

  // 登出
  async logout() {
    const idToken = localStorage.getItem('id_token')
    
    // 清除本地存储
    localStorage.removeItem('access_token')
    localStorage.removeItem('id_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('user_info')
    
    // 重定向到OIDC登出端点
    if (idToken) {
      const logoutUrl = `${oidcConfig.issuer}${oidcConfig.endpoints.logout}?id_token_hint=${idToken}&post_logout_redirect_uri=${window.location.origin}`
      window.location.href = logoutUrl
    }
  }

  // 检查是否已登录
  isAuthenticated() {
    const token = localStorage.getItem('access_token')
    if (!token) return false
    
    try {
      const payload = JSON.parse(atob(token.split('.')[1]))
      return payload.exp > Date.now() / 1000
    } catch {
      return false
    }
  }

  // 获取用户信息
  getUserInfo() {
    const userInfo = localStorage.getItem('user_info')
    return userInfo ? JSON.parse(userInfo) : null
  }

  // 生成随机字符串
  generateRandomString(length = 32) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let result = ''
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
  }
}

export default new AuthService()